package com.woparker.kiosk.utils;

import android.content.Context;
import android.util.Log;


import com.woparker.kiosk.bean.MapGroupBean;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by yuanxd on 2017/9/26 0026.
 */
public class FileHandler {
    private Context context;
    public FileHandler(Context context) {
        this.context = context;
    }

    //存储数据到文件
    public void saveName(String name) throws Exception {
        //context.getFilesDir();// 得到存放文件的系统目录 /data/data/<package name>/files
        //context.getCacheDir(); //缓存目录  /data/data/<package name>/cache
        FileOutputStream outputStream = context.openFileOutput("deomfilerw.txt", Context.MODE_APPEND);
        outputStream.write(name.getBytes());
        outputStream.close();
    }

    //存储数据到sdcard
    public void saveNameToSDCard(String fileName, String name) throws Exception {
        File file = new File("/sdcard/tenetmap", fileName);
        if (!file.getParentFile().exists()) { //如果该文件夹不存在，则进行创建
            file.getParentFile().mkdirs();//创建文件夹
        }
        FileOutputStream outputStream = new FileOutputStream(file);
        outputStream.write(name.getBytes());
        outputStream.close();
    }

    //读取数据到
    public String getNameToSDCard(String fileName) throws Exception {
        File file = new File("/sdcard/tenetmap", fileName);
        if (!file.getParentFile().exists()) { //如果该文件夹不存在，则进行创建
            file.getParentFile().mkdirs();//创建文件夹
        }
        FileInputStream inputStream = new FileInputStream(file);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        byte[] data = outStream.toByteArray();
        String name = new String(data);
        return name;
    }

    // 读取数据
    public String getName() throws Exception {
        FileInputStream inputStream = context.openFileInput("deomfilerw.txt");
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        byte[] data = outStream.toByteArray();
        String name = new String(data);
        return name;
    }

    /**
     * @param mapGroupData 文本数据
     */
    public MapGroupBean analyzeData(String mapGroupData) {
        int length = mapGroupData.length();
        MapGroupBean groupBean = new MapGroupBean();
        int mapIndex = mapGroupData.indexOf("map");
        int numberIndex = mapGroupData.indexOf("[");
        int startBigBracketIndex = mapGroupData.indexOf("{");
        int endBigBracketIndex = mapGroupData.lastIndexOf("}");
        int blockSize = Integer.parseInt(mapGroupData.substring(mapIndex + 3, numberIndex));
        groupBean.setBlockSize(blockSize);
        //获取地图内容数据
        String content = mapGroupData.substring(startBigBracketIndex + 1, endBigBracketIndex);
        //去掉换行符
        content = CommonUtils.replaceBlank(content);
        //去掉最后一个字符串
        content = content.substring(0, content.length() - 1);
        //根据},截取字符串数组
        String[] groupOne = content.split("\\}\\,");
        //获取列
        int col = groupOne.length;
        groupBean.setCol(col);
        //获取行
        int row = 0;
        //构建地图数组
        int[][] map = new int[0][];
        for (int i = 0; i < col; i++) {
            String groupItem = groupOne[i];
            groupItem = groupItem.substring(1);
            String[] groupTwo = groupItem.split(",");
            if(row == 0){
                row = groupTwo.length;
                groupBean.setRow(row);
                map = new int[col][row];
            }
            for (int k = 0; k < row; k++) {
                map[i][k] = Integer.parseInt(groupTwo[k]);
            }
        }
        Log.e("FileHandler","map[i][k]:" + map);
        groupBean.setMap(map);
        return groupBean;
    }

    public static void doSaveFileInDefaultFileDir(Context context, String filename, byte[] bb) {
        //1.首先判断文件是否存在，存在就什么都不做，不存在就保存它
        File file = new File(context.getFilesDir(), filename);
        if (!file.exists()) {
            try {
                file.createNewFile();
                FileOutputStream fout = new FileOutputStream(file);
                fout.write(bb);
                fout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    StringBuffer mapDataBuffer;

    /**
     * 读取文本文件
     *
     * @param urlStr url路径
     * @return 文本信息
     * 根据url下载文件，前提是这个文件中的内容是文本，
     * 1.创建一个URL对象
     * 2.通过URL对象，创建一个Http连接
     * 3.得到InputStream
     * 4.从InputStream中得到数据
     */
    public void download(final String urlStr, final OnMapDownloadListener onMapDownloadListener) {
        mapDataBuffer= new StringBuffer();
        new Thread() {
            public void run() {
                String line = null;
                BufferedReader bufferedReader = null;
                URL url;
                try {
                    url = new URL(urlStr);
                    //创建http连接
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    //使用IO流读取数据
                    bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    while ((line = bufferedReader.readLine()) != null) {
                        mapDataBuffer.append(line);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (null != bufferedReader)
                            bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Log.e("FileHandler","下载txt文件");
                onMapDownloadListener.onLoad(mapDataBuffer.toString());
            }
        }.start();
    }


    public interface OnMapDownloadListener {
        void onLoad(String result);
    }
}

